package com.gg.interceptor;

import com.gg.pojo.User;
import com.gg.utils.JwtUtils;
import com.gg.utils.RsaUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;

/**
 * @Auther: YDYX
 * @Date: 2022/1/11 - 01 - 11 - 21:50
 * @Description: com.gg.interceptor
 * @version: 1.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token信息
        String method = request.getMethod();
        if (method.equals("OPTIONS")){
            return true;
        }

        String token = request.getHeader("token");
        //校验token
        try {
            PublicKey publicKey = RsaUtils.getPublicKey(ResourceUtils.getFile("classpath:rsa.pub").getPath());
            JwtUtils.getInfoFromToken(token, publicKey, User.class);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            //校验失败
            response.sendRedirect(request.getContextPath()+"user/tokenError");
            return false;
        }
    }
}
